package com.ruoyi.common.utils.http;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

/**
 * http、https 请求工具类， 微信为https的请求
 *
 * @author yehx
 */
public class HttpUtil {

    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final String _GET = "GET"; // GET
    private static final String _POST = "POST";// POST

    /**
     * 初始化http请求参数
     *
     * @param url
     * @param method
     * @param headers
     * @return
     * @throws Exception
     */
    private static HttpURLConnection initHttp(String url, String method,
                                              Map<String, String> headers) throws Exception {
        URL _url = new URL(url);
        HttpURLConnection http = (HttpURLConnection) _url.openConnection();
        // 连接超时
        http.setConnectTimeout(DEF_CONN_TIMEOUT);
        // 读取超时 --服务器响应比较慢，增大时间
        http.setReadTimeout(DEF_READ_TIMEOUT);
        http.setUseCaches(false);
        http.setRequestMethod(method);
        http.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        http.setRequestProperty(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
        if (null != headers && !headers.isEmpty()) {
            for (Entry<String, String> entry : headers.entrySet()) {
                http.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        http.setDoOutput(true);
        http.setDoInput(true);
        http.connect();
        return http;
    }

    /**
     * 初始化http请求参数
     *
     * @param url
     * @param method
     * @return
     * @throws Exception
     */
    private static HttpsURLConnection initHttps(String url, String method,
                                                Map<String, String> headers) throws Exception {
        TrustManager[] tm = {new MyX509TrustManager()};
        System.setProperty("https.protocols", "TLSv1");
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tm, new java.security.SecureRandom());
        // 从上述SSLContext对象中得到SSLSocketFactory对象
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        URL _url = new URL(url);
        HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
        // 设置域名校验
        http.setHostnameVerifier(new HttpUtil().new TrustAnyHostnameVerifier());
        // 连接超时
        http.setConnectTimeout(DEF_CONN_TIMEOUT);
        // 读取超时 --服务器响应比较慢，增大时间
        http.setReadTimeout(DEF_READ_TIMEOUT);
        http.setUseCaches(false);
        http.setRequestMethod(method);
        http.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        http.setRequestProperty(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
        if (null != headers && !headers.isEmpty()) {
            for (Entry<String, String> entry : headers.entrySet()) {
                http.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        http.setSSLSocketFactory(ssf);
        http.setDoOutput(true);
        http.setDoInput(true);
        http.connect();
        return http;
    }

    /**
     * @return 返回类型:
     * @throws Exception
     * @description 功能描述: get 请求
     */
    public static String get(String url, Map<String, String> params,
                             Map<String, String> headers) throws Exception {
        HttpURLConnection http = null;
        if (isHttps(url)) {
            http = initHttps(initParams(url, params), _GET, headers);
        } else {
            http = initHttp(initParams(url, params), _GET, headers);
        }
        InputStream in = http.getInputStream();
        BufferedReader read = new BufferedReader(new InputStreamReader(in,
                DEFAULT_CHARSET));
        String valueString = null;
        StringBuffer bufferRes = new StringBuffer();
        while ((valueString = read.readLine()) != null) {
            bufferRes.append(valueString);
        }
        in.close();
        if (http != null) {
            http.disconnect();// 关闭连接
        }
        return bufferRes.toString();
    }

    public static String get(String url) throws Exception {
        return get(url, null);
    }

    public static String get(String url, Map<String, String> params)
            throws Exception {
        return get(url, params, null);
    }

    public static String post(String url, String params)
            throws Exception {
        HttpURLConnection http = null;
        if (isHttps(url)) {
            http = initHttps(url, _POST, null);
        } else {
            http = initHttp(url, _POST, null);
        }
        OutputStream out = http.getOutputStream();
        out.write(params.getBytes(DEFAULT_CHARSET));
        out.flush();
        out.close();

        InputStream in = http.getInputStream();
        BufferedReader read = new BufferedReader(new InputStreamReader(in,
                DEFAULT_CHARSET));
        String valueString = null;
        StringBuffer bufferRes = new StringBuffer();
        while ((valueString = read.readLine()) != null) {
            bufferRes.append(valueString);
        }
        in.close();
        if (http != null) {
            http.disconnect();// 关闭连接
        }
        return bufferRes.toString();
    }

    /**
     * 功能描述: 构造请求参数
     *
     * @return 返回类型:
     * @throws Exception
     */
    public static String initParams(String url, Map<String, String> params)
            throws Exception {
        if (null == params || params.isEmpty()) {
            return url;
        }
        StringBuilder sb = new StringBuilder(url);
        if (url.indexOf("?") == -1) {
            sb.append("?");
        }
        sb.append(map2Url(params));
        return sb.toString();
    }

    /**
     * map构造url
     *
     * @return 返回类型:
     * @throws Exception
     */
    public static String map2Url(Map<String, String> paramToMap)
            throws Exception {
        if (null == paramToMap || paramToMap.isEmpty()) {
            return null;
        }
        StringBuffer url = new StringBuffer();
        boolean isfist = true;
        for (Entry<String, String> entry : paramToMap.entrySet()) {
            if (isfist) {
                isfist = false;
            } else {
                url.append("&");
            }
            url.append(entry.getKey()).append("=");
            String value = entry.getValue();
            if (!StringUtils.isEmpty(value)) {
                url.append(URLEncoder.encode(value, DEFAULT_CHARSET));
            }
        }
        return url.toString();
    }

    /**
     * 检测是否https
     *
     * @param url
     */
    private static boolean isHttps(String url) {
        return url.startsWith("https");
    }

    public static void main(String[] args) {
        //1111771654  L9dY11VbWry3TF6J c1166a86d983993f7510350683e9eb0f
        String s1 = "https://api.q.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
        String s = null; // "c73c5bab0517eea38a7cfb491c2ceb1c"
        String GET_TOUTIAO_LOGIN_INFO_URL = "https://developer.toutiao.com/api/apps/jscode2session?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
        try {
            s = HttpUtil.get(String.format(s1, "1111771654", "L9dY11VbWry3TF6J",
                    "c73c5bab0517eea38a7cfb491c2ceb1c"));
            // s=    HttpUtil.get(String.format(GET_TOUTIAO_LOGIN_INFO_URL, "tt32884435adb0b8c701", "c88c04453281b8df7180ac019e7a442b518f2f96",
            //         "GVDPBxMfUaYfbXzrTHAqeqywqstA6nqfc_FoKmmgbkMY25KVNfa5zZp4OznPPKSOF7TQUyEU7lGH_Rs9AeLUbTdvuXgPSpRY9SfpfdXlm5GImDRkl3yEy-JkKfc"));

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(JSONObject.parseObject(s));
        String url = "http://apiv3.yangkeduo.com/operation/14/groups";
        String rspStr = HttpUtils.sendGet(url, "page=1&size=100&opt_type=1");
        JSONObject obj = JSONObject.parseObject(rspStr);
        JSONArray region = obj.getJSONArray("goods_list");
        // {"goods_name":"本命牛年衣服2021红色新年卫衣暴富情侣装拜年服加绒加厚女男冬季","thumb_url":"http://t00img.yangkeduo.com/goods/images/2021-01-11/55cc05fda3c2eb92108c2649af85aad5.jpeg",
        // "hd_thumb_wm":"","country":"","sales_tip":"已拼6381件","icon":{"width":"133","id":"20013","tag_series":"2",
        // "url":"https://commimg.pddpic.com/oms_img_ng/2021-01-28/642e4467-c0c0-4986-b8a6-9b5290a7f6e3.png","height":"45"},
        // "cnt":6381,"goods_id":215360622164,"hd_thumb_url":"http://t00img.yangkeduo.com/goods/images/2021-01-11/3b53f9e86cac830d6fb5b9a9eac8094f.jpeg",
        // "event_type":0,"normal_price":5290,"p_rec":{"sec_info":"3D9F27CB3016FA3365666E0B6F1160F0","list_id":"fenlei_gyl_818027987__14","bk":"75","vid":"djAuMC4y4oeoMjQ0OTM1ODc4MDY0MDkzNDIwOA==","experiment":"{\"4033\":{\"g\":\"4033_0User\",\"bk\":\"30\"},\"4079\":{\"g\":\"4079_0User\",\"bk\":\"17\"},\"4112\":{\"g\":\"4112_0User\",\"bk\":\"68\"},\"3361\":{\"g\":\"3361_0User\",\"bk\":\"96\"},\"4092\":{\"g\":\"4092_0User\",\"bk\":\"66\"},\"3184\":{\"g\":\"3184_0User\",\"bk\":\"71\"},\"3261\":{\"g\":\"3261_0_base\",\"bk\":\"11\"},\"3260\":{\"g\":\"3260_V3\",\"bk\":\"33\"},\"3614\":{\"g\":\"3614_defaultGroup\",\"bk\":\"10\"},\"3818\":{\"g\":\"3818_0User\",\"bk\":\"61\"},\"3157\":{\"g\":\"3157_expGroup\",\"bk\":\"26\"},\"3891\":{\"g\":\"3891_0User\",\"bk\":\"48\"},\"3156\":{\"g\":\"3156_0User\",\"bk\":\"90\"},\"3232\":{\"g\":\"3232_0User\",\"bk\":\"50\"},\"3472\":{\"g\":\"3472_user0\",\"bk\":\"90\"},\"3151\":{\"g\":\"3151_0User\",\"bk\":\"78\"},\"3150\":{\"g\":\"3150_0User\",\"bk\":\"43\"},\"3270\":{\"g\":\"3270_0_base\",\"bk\":\"37\"},\"0\":{\"g\":\"DEFAULT\",\"bk\":\"19\"},\"3548\":{\"g\":\"3548_0User\",\"bk\":\"97\"},\"3522\":{\"g\":\"3522_0_base\",\"bk\":\"9\"},\"3267\":{\"g\":\"3267_0User\",\"bk\":\"6\"},\"3465\":{\"g\":\"3465_0User\",\"bk\":\"75\"},\"3487\":{\"g\":\"3487_0User\",\"bk\":\"94\"},\"3702\":{\"g\":\"3702_0User\",\"bk\":\"89\"},\"3209\":{\"g\":\"3209_0User\",\"bk\":\"52\"},\"3967\":{\"g\":\"3967_0User\",\"bk\":\"66\"},\"3528\":{\"g\":\"3528_unused\",\"bk\":\"78\"}}","pvid":"3e94548f-f7c6-4f23-941e-eb6084d858f21612587680041","price":"5090.0","zyw":"false","owner":"scene","set":"shb1","org":"rec","sceneName":"fenlei","g":"carrier","goods_id":"215360622164","opt1":"14","m":"8B32CC8C9F0AC2114B788FB092B3C6A0","opt_id":"14","app_name":"fenlei_gyl","te":"1612587680195","t":"70A63CC217483AF0D0700F500CCF595C","stage":"1","rpd_scene":"index_opt","request_id":"5186cda1-e474-45db-853c-223ec717f145","ab_id":"ZvEZbmAR","ts":"1612587680038"},"tag_list":[{"text":"立减2元","text_color":"#E02E24","type":4047,"tag_track_info":"4&null"}],"link_url":"goods.html?goods_id=215360622164","market_price":8880,"image_wm":"","short_name":"本命牛年衣服2021红色新年卫衣暴富情侣装拜年服加绒加厚女男冬季","thumb_wm":"","tag":-1,"group":{"price":5090,"customer_num":2}}
        for (int i = 0; i < region.size(); i++) {
            System.out.println(region.getJSONObject(i));
            //System.out.println(region.getJSONObject(i).get("goods_name"));

        }

    }

    /**
     * https 域名校验
     *
     * @return
     */
    public class TrustAnyHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;// 直接返回true
        }
    }
}